<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="ios," />





  <link rel="alternate" href="/atom.xml" title="搁浅丶岁月的变迁" type="application/atom+xml" />






<meta name="description" content="ReactiveCocoa基础 本文修改自最快让你上手ReactiveCocoa之基础篇 有关对 ReactiveCocoa 的看法可以看一下唐巧的这篇ReactiveCocoa 讨论会   ReactiveCocoa简介 ReactiveCocoa（简称为RAC）,是由Github开源的一个应用于iOS和OS开发的新框架,Cocoa是苹果整套框架的简称，因此很多苹果框架喜欢以Cocoa结尾。 在">
<meta name="keywords" content="ios">
<meta property="og:type" content="article">
<meta property="og:title" content="ReactiveCocoa 基础">
<meta property="og:url" content="http://yoursite.com/2016/12/26/2016-12-26-ReactiveCocoa-基础/index.html">
<meta property="og:site_name" content="搁浅丶岁月的变迁">
<meta property="og:description" content="ReactiveCocoa基础 本文修改自最快让你上手ReactiveCocoa之基础篇 有关对 ReactiveCocoa 的看法可以看一下唐巧的这篇ReactiveCocoa 讨论会   ReactiveCocoa简介 ReactiveCocoa（简称为RAC）,是由Github开源的一个应用于iOS和OS开发的新框架,Cocoa是苹果整套框架的简称，因此很多苹果框架喜欢以Cocoa结尾。 在">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://ww2.sinaimg.cn/large/006y8lVagw1fb7g0gukk8j30m90rl78j.jpg">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/006y8lVagw1fb7g6on3iwj30c2029q2z.jpg">
<meta property="og:updated_time" content="2018-03-08T07:33:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ReactiveCocoa 基础">
<meta name="twitter:description" content="ReactiveCocoa基础 本文修改自最快让你上手ReactiveCocoa之基础篇 有关对 ReactiveCocoa 的看法可以看一下唐巧的这篇ReactiveCocoa 讨论会   ReactiveCocoa简介 ReactiveCocoa（简称为RAC）,是由Github开源的一个应用于iOS和OS开发的新框架,Cocoa是苹果整套框架的简称，因此很多苹果框架喜欢以Cocoa结尾。 在">
<meta name="twitter:image" content="http://ww2.sinaimg.cn/large/006y8lVagw1fb7g0gukk8j30m90rl78j.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2016/12/26/2016-12-26-ReactiveCocoa-基础/"/>





  <title>ReactiveCocoa 基础 | 搁浅丶岁月的变迁</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/liaoren512"><img style="position: absolute; top: 0; left: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_left_red_aa0000.png" alt="Fork me on GitHub"></a>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">搁浅丶岁月的变迁</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">没有虽败犹荣，只有成王败寇。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2016/12/26/2016-12-26-ReactiveCocoa-基础/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="廖壬">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/ichgo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="搁浅丶岁月的变迁">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ReactiveCocoa 基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-12-26T00:00:00+08:00">
                2016-12-26
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="ReactiveCocoa基础"><a href="#ReactiveCocoa基础" class="headerlink" title="ReactiveCocoa基础"></a>ReactiveCocoa基础</h1><blockquote>
<p>本文修改自<a href="http://www.jianshu.com/p/87ef6720a096" target="_blank" rel="noopener">最快让你上手ReactiveCocoa之基础篇</a></p>
<p>有关对 <strong>ReactiveCocoa</strong> 的看法可以看一下唐巧的这篇<a href="https://gold.xitu.io/entry/568bd2ae60b2e57ba2cd2c7b" target="_blank" rel="noopener">ReactiveCocoa 讨论会</a></p>
</blockquote>
<p><img src="http://ww2.sinaimg.cn/large/006y8lVagw1fb7g0gukk8j30m90rl78j.jpg" alt="ReactiveCocoa思维导图"></p>
<h1 id="ReactiveCocoa简介"><a href="#ReactiveCocoa简介" class="headerlink" title="ReactiveCocoa简介"></a>ReactiveCocoa简介</h1><p><a href="https://github.com/ReactiveCocoa/ReactiveCocoa" target="_blank" rel="noopener"><img src="http://ww1.sinaimg.cn/large/006y8lVagw1fb7g6on3iwj30c2029q2z.jpg" alt=""></a></p>
<p>ReactiveCocoa（简称为RAC）,是由Github开源的一个应用于iOS和OS开发的新框架,Cocoa是苹果整套框架的简称，因此很多苹果框架喜欢以Cocoa结尾。</p>
<p>在我们iOS开发过程中，当某些事件响应的时候，需要处理某些业务逻辑,这些事件都用不同的方式来处理。</p>
<p>比如按钮的点击使用action，ScrollView滚动使用delegate，属性值改变使用KVO等系统提供的方式。其实这些事件，都可以通过RAC处理</p>
<p>ReactiveCocoa为事件提供了很多处理方法，而且利用RAC处理事件很方便，可以把要处理的事情，和监听的事情的代码放在一起，这样非常方便我们管理，就不需要跳到对应的方法里。</p>
<p>非常符合我们开发中高聚合，低耦合的思想。</p>
<h1 id="ReactiveCocoa编程思想"><a href="#ReactiveCocoa编程思想" class="headerlink" title="ReactiveCocoa编程思想"></a>ReactiveCocoa编程思想</h1><p>在开发中我们也不能太依赖于某个框架，否则这个框架不更新了，导致项目后期没办法维护，比如之前Facebook提供的 <code>Three20</code> 框架，在当时也是神器，但是后来不更新了，也就没什么人用了。因此我感觉学习一个框架，还是有必要了解它的编程思想。</p>
<p>先简单介绍下目前咱们已知的编程思想:</p>
<h4 id="响应式编程思想"><a href="#响应式编程思想" class="headerlink" title="响应式编程思想"></a>响应式编程思想</h4><p><strong>响应式编程思想</strong>：不需要考虑调用顺序，只需要知道考虑结果，类似于蝴蝶效应，产生一个事件，会影响很多东西，这些事件像流一样的传播出去，然后影响结果，借用面向对象的一句话，万物皆是流。</p>
<p><code>代表</code>：KVO</p>
<h4 id="链式编程思想"><a href="#链式编程思想" class="headerlink" title="链式编程思想"></a>链式编程思想</h4><p><strong>链式编程</strong> 是将多个操作（多行代码）通过点号(.)链接在一起成为一句代码,使代码可读性好。如:</p>
<figure class="highlight gcode"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">make.add<span class="comment">(1)</span>.add<span class="comment">(2)</span>.<span class="keyword">sub</span><span class="comment">(5)</span>.muilt<span class="comment">(-4)</span>.divide<span class="comment">(4)</span>;</span><br></pre></td></tr></table></figure>
<p><code>特点</code>：方法的返回值是block,block必须有返回值（本身对象），block参数（需要操作的值）</p>
<p><code>代表</code>：masonry框架。</p>
<p><code>实现</code>：模仿masonry，写一个加法计算器，练习链式编程思想。</p>
<p>NSObject+Caculator.h</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># import <span class="meta-string">&lt;Foundation/Foundation.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@class</span> <span class="title">CaculatorMaker</span>;</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">NSObject</span> (<span class="title">Caculator</span>)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 计算</span></span><br><span class="line">+ (<span class="keyword">int</span>)makeCaculators:(<span class="keyword">void</span> (^)(CaculatorMaker *))block;</span><br><span class="line">                       </span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<p>NSObject+Caculator.m</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">@implementation <span class="type">NSObject</span> (<span class="type">Caculator</span>)</span><br><span class="line"></span><br><span class="line">+ (<span class="built_in">int</span>)makeCaculators:(<span class="built_in">void</span> (^)(<span class="type">CaculatorMaker</span> *))<span class="keyword">block</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="type">CaculatorMaker</span> *mgr = [[<span class="type">CaculatorMaker</span> alloc] init];</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">block</span>(mgr);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> (mgr.<span class="literal">result</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@<span class="keyword">end</span></span><br></pre></td></tr></table></figure>
<p>CaculatorMaker.h</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># import <span class="meta-string">&lt;Foundation/Foundation.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@class</span> <span class="title">CaculatorMaker</span>;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">typedef</span> CaculatorMaker *(^CasulatorBlock)(<span class="keyword">int</span>);</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">CaculatorMaker</span> : <span class="title">NSObject</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">assign</span>) <span class="keyword">int</span> result;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 算数方法</span></span><br><span class="line">- (CaculatorMaker *(^)(<span class="keyword">int</span>))add;</span><br><span class="line">- (CasulatorBlock)sub;</span><br><span class="line">- (CasulatorBlock)muilt;</span><br><span class="line">- (CasulatorBlock)divide;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<p>CaculatorMaker.m</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta"># import "CaculatorMaker.h"</span></span><br><span class="line"></span><br><span class="line">@implementation CaculatorMaker</span><br><span class="line"></span><br><span class="line">- (CaculatorMaker *(^)(<span class="keyword">int</span>))<span class="keyword">add</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> ^CaculatorMaker *(<span class="keyword">int</span> <span class="keyword">value</span>) &#123;</span><br><span class="line">        </span><br><span class="line">        _result += <span class="keyword">value</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> self;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (CasulatorBlock)sub &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> ^CaculatorMaker *(<span class="keyword">int</span> <span class="keyword">value</span>) &#123;</span><br><span class="line">        </span><br><span class="line">        _result -= <span class="keyword">value</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> self;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (CasulatorBlock)muilt &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> ^CaculatorMaker *(<span class="keyword">int</span> <span class="keyword">value</span>) &#123;</span><br><span class="line">        </span><br><span class="line">        _result *= <span class="keyword">value</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> self;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">- (CasulatorBlock)divide &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> ^CaculatorMaker *(<span class="keyword">int</span> <span class="keyword">value</span>) &#123;</span><br><span class="line">        </span><br><span class="line">        _result /= <span class="keyword">value</span>;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> self;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">@end</span><br></pre></td></tr></table></figure>
<p>使用：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> result = [NSObject makeCaculators:^(CaculatorMaker *make) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// ( 1 + 2 - 5 ) * (-4) / 4</span></span><br><span class="line">        make.<span class="keyword">add</span>(<span class="number">1</span>).<span class="keyword">add</span>(<span class="number">2</span>).sub(<span class="number">5</span>).muilt(<span class="number">-4</span>).divide(<span class="number">4</span>);</span><br><span class="line"></span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">    NSLog(<span class="string">@"%d"</span>, result);</span><br></pre></td></tr></table></figure>
<h4 id="函数式编程思想"><a href="#函数式编程思想" class="headerlink" title="函数式编程思想"></a>函数式编程思想</h4><p><strong>函数式编程思想</strong>：是把操作尽量写成一系列嵌套的函数或者方法调用。</p>
<p><code>特点</code>：每个方法必须有返回值（本身对象）,把函数或者Block当做参数,block参数（需要操作的值）block返回值（操作结果）</p>
<p><code>代表</code>：<strong>ReactiveCocoa</strong></p>
<p><code>实现</code>：用函数式编程实现，写一个加法计算器,并且加法计算器自带判断是否等于某个值.</p>
<figure class="highlight nimrod"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Calculator</span> *caculator = [[<span class="type">Calculator</span> alloc] init];</span><br><span class="line"></span><br><span class="line"><span class="type">BOOL</span> isqule = [[[caculator caculator:^<span class="built_in">int</span>(<span class="built_in">int</span> <span class="literal">result</span>) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="literal">result</span> += <span class="number">2</span>;</span><br><span class="line">    <span class="literal">result</span> *= <span class="number">5</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">result</span>;</span><br><span class="line">    </span><br><span class="line">&#125;] equle:^<span class="type">BOOL</span>(<span class="built_in">int</span> <span class="literal">result</span>) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">result</span> == <span class="number">10</span>;</span><br><span class="line">    </span><br><span class="line">&#125;] isEqule];</span><br><span class="line"></span><br><span class="line"><span class="type">NSLog</span>(@<span class="string">"%d"</span>, isqule);</span><br></pre></td></tr></table></figure>
<p>Calculator.h</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#import <span class="meta-string">&lt;Foundation/Foundation.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">Calculator</span> : <span class="title">NSObject</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">assign</span>) <span class="built_in">BOOL</span> isEqule;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">assign</span>) <span class="keyword">int</span> result;</span><br><span class="line"></span><br><span class="line">- (Calculator *)caculator:(<span class="keyword">int</span> (^)(<span class="keyword">int</span> result))caculator;</span><br><span class="line"></span><br><span class="line">- (Calculator *)equle:(<span class="built_in">BOOL</span> (^)(<span class="keyword">int</span> result))operation;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<p>Calculator.m</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#import <span class="meta-string">"Calculator.h"</span></span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">Calculator</span></span></span><br><span class="line"></span><br><span class="line">- (Calculator *)caculator:(<span class="keyword">int</span> (^)(<span class="keyword">int</span>))caculator &#123;</span><br><span class="line"></span><br><span class="line">    _result = caculator(_result);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">- (Calculator *)equle:(<span class="built_in">BOOL</span> (^)(<span class="keyword">int</span>))operation &#123;</span><br><span class="line"></span><br><span class="line">    _isEqule = operation(_result);</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">self</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<p><strong>ReactiveCocoa</strong> 结合了这两种种编程风格：</p>
<ul>
<li><p><strong>函数式编程</strong>（Functional Programming）</p>
</li>
<li><p><strong>响应式编程</strong>（Reactive Programming）</p>
</li>
</ul>
<p>所以，你可能听说过 <strong>ReactiveCocoa</strong> 被描述为函数响应式编程（FRP）框架。</p>
<p>以后使用RAC解决问题，就不需要考虑调用顺序，直接考虑结果，把每一次操作都写成一系列嵌套的方法中，使代码高聚合，方便管理。</p>
<h1 id="导入ReactiveCocoa"><a href="#导入ReactiveCocoa" class="headerlink" title="导入ReactiveCocoa"></a>导入ReactiveCocoa</h1><hr>
<blockquote>
<p>ReactiveCocoa的<a href="https://github.com/ReactiveCocoa/ReactiveCocoa" target="_blank" rel="noopener">GitHub地址</a></p>
</blockquote>
<h4 id="Objective-C"><a href="#Objective-C" class="headerlink" title="Objective-C"></a>Objective-C</h4><p><strong>ReactiveCocoa 2.5</strong>版本以后改用了<strong>Swift</strong>，所以<strong>Objective-C</strong>项目需要导入<strong>2.5版本</strong></p>
<p><code>CocoaPods</code>集成：</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">platform</span> :ios, <span class="string">'8.0'</span></span><br><span class="line"></span><br><span class="line">target <span class="string">'YouProjectName'</span> <span class="keyword">do</span></span><br><span class="line"></span><br><span class="line">use_frameworks!</span><br><span class="line">pod <span class="string">'ReactiveCocoa'</span>, <span class="string">'~&gt; 2.5'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>
<p>PS:新版本的<code>CocoaPods</code>需要加入</p>
<figure class="highlight ada"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">target <span class="symbol">'YouProjectName</span>' <span class="keyword">do</span> </span><br><span class="line">... </span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>
<p>这句话来限定项目，否则导入失败。</p>
<h4 id="Swift"><a href="#Swift" class="headerlink" title="Swift"></a>Swift</h4><p><strong>Swift</strong>项目导入2.5后的版本</p>
<figure class="highlight delphi"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">platform</span> :ios, <span class="string">'8.0'</span></span><br><span class="line"></span><br><span class="line">target <span class="string">'YouProjectName'</span> <span class="keyword">do</span></span><br><span class="line"></span><br><span class="line">use_frameworks!</span><br><span class="line">pod <span class="string">'ReactiveCocoa'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>
<p>使用时在<a href="http://www.jianshu.com/p/587b83b6665c" target="_blank" rel="noopener">全局头文件</a>导入头文件即可</p>
<p><code>PrefixHeader.pch</code></p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">ifndef</span> PrefixHeader_pch</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> PrefixHeader_pch</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#import <span class="meta-string">&lt;ReactiveCocoa/ReactiveCocoa.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">endif</span></span></span><br></pre></td></tr></table></figure>
<h1 id="ReactiveCocoa常见类"><a href="#ReactiveCocoa常见类" class="headerlink" title="ReactiveCocoa常见类"></a>ReactiveCocoa常见类</h1><h4 id="RACSiganl-信号类"><a href="#RACSiganl-信号类" class="headerlink" title="RACSiganl 信号类"></a>RACSiganl 信号类</h4><blockquote>
<p>信号类,一般表示将来有数据传递，只要有数据改变，信号内部接收到数据，就会马上发出数据。</p>
</blockquote>
<p>注意：</p>
<ul>
<li>信号类(RACSiganl)，只是表示当数据改变时，信号内部会发出数据，它本身不具备发送信号的能力，而是交给内部一个订阅者去发出。</li>
<li>默认一个信号都是冷信号，也就是值改变了，也不会触发，只有订阅了这个信号，这个信号才会变为热信号，值改变了才会触发。</li>
<li>如何订阅信号：调用信号RACSignal的subscribeNext就能订阅</li>
</ul>
<p>使用：</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// RACSignal使用步骤：</span></span><br><span class="line">    <span class="comment">// 1.创建信号 + (RACSignal *)createSignal:(RACDisposable * (^)(id&lt;RACSubscriber&gt; subscriber))didSubscribe</span></span><br><span class="line">    <span class="comment">// 2.订阅信号,才会激活信号. - (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock</span></span><br><span class="line">    <span class="comment">// 3.发送信号 - (void)sendNext:(id)value</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">// RACSignal底层实现：</span></span><br><span class="line">    <span class="comment">// 1.创建信号，首先把didSubscribe保存到信号中，还不会触发。</span></span><br><span class="line">    <span class="comment">// 2.当信号被订阅，也就是调用signal的subscribeNext:nextBlock</span></span><br><span class="line">    <span class="comment">// 2.2 subscribeNext内部会创建订阅者subscriber，并且把nextBlock保存到subscriber中。</span></span><br><span class="line">    <span class="comment">// 2.1 subscribeNext内部会调用siganl的didSubscribe</span></span><br><span class="line">    <span class="comment">// 3.siganl的didSubscribe中调用[subscriber sendNext:@1];</span></span><br><span class="line">    <span class="comment">// 3.1 sendNext底层其实就是执行subscriber的nextBlock</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 1.创建信号</span></span><br><span class="line">    RACSignal *siganl = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// block调用时刻：每当有订阅者订阅信号，就会调用block。</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 2.发送信号</span></span><br><span class="line">        [subscriber <span class="string">sendNext:</span>@<span class="number">1</span>];</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 如果不在发送数据，最好发送信号完成，内部会自动调用[RACDisposable disposable]取消订阅信号。</span></span><br><span class="line">        [subscriber sendCompleted];</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> [RACDisposable <span class="string">disposableWithBlock:</span>^&#123;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// block调用时刻：当信号发送完成或者发送错误，就会自动执行这个block,取消订阅信号。</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">// 执行完Block后，当前信号就不在被订阅了。</span></span><br><span class="line"></span><br><span class="line">            NSLog(@<span class="string">"信号被销毁"</span>);</span><br><span class="line"></span><br><span class="line">        &#125;];</span><br><span class="line">    &#125;];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3.订阅信号,才会激活信号.</span></span><br><span class="line">    [siganl <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">        <span class="comment">// block调用时刻：每当有信号发出数据，就会调用block.</span></span><br><span class="line">        NSLog(@<span class="string">"接收到数据:%@"</span>,x);</span><br><span class="line">    &#125;];</span><br></pre></td></tr></table></figure>
<h4 id="RACSubscriber"><a href="#RACSubscriber" class="headerlink" title="RACSubscriber"></a>RACSubscriber</h4><blockquote>
<p>表示订阅者的意思，用于发送信号，这是一个协议，不是一个类，只要遵守这个协议，并且实现方法才能成为订阅者。通过create创建的信号，都有一个订阅者，帮助他发送数据。</p>
</blockquote>
<h4 id="RACDisposable"><a href="#RACDisposable" class="headerlink" title="RACDisposable"></a>RACDisposable</h4><blockquote>
<p>用于取消订阅或者清理资源，当信号发送完成或者发送错误的时候，就会自动触发它。</p>
</blockquote>
<p><strong>使用场景</strong>：不想监听某个信号时，可以通过它主动取消订阅信号。</p>
<h4 id="RACSubject"><a href="#RACSubject" class="headerlink" title="RACSubject"></a>RACSubject</h4><blockquote>
<p>RACSubject:信号提供者，自己可以充当信号，又能发送信号。</p>
</blockquote>
<p><strong>使用场景</strong>:通常用来代替代理，有了它，就不必要定义代理了。</p>
<h4 id="RACReplaySubject"><a href="#RACReplaySubject" class="headerlink" title="RACReplaySubject"></a><strong>RACReplaySubject</strong></h4><blockquote>
<p>重复提供信号类，RACSubject的子类。</p>
</blockquote>
<p><code>RACReplaySubject</code>与<code>RACSubject</code>区别:</p>
<p> <code>RACReplaySubject</code>可以先发送信号，在订阅信号，<code>RACSubject</code>就不可以。</p>
<p> <strong>使用场景一</strong>:如果一个信号每被订阅一次，就需要把之前的值重复发送一遍，使用重复提供信号类。</p>
<p> <strong>使用场景二</strong>:可以设置capacity数量来限制缓存的value的数量,即只缓充最新的几个值。</p>
<p> <strong>ACSubject</strong> 和 <strong>RACReplaySubject</strong> 简单使用：</p>
<p> <strong>ACSubject</strong></p>
 <figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// RACSubject使用步骤</span></span><br><span class="line"><span class="comment">// 1.创建信号 [RACSubject subject]，跟RACSiganl不一样，创建信号时没有block。</span></span><br><span class="line"><span class="comment">// 2.订阅信号 - (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock</span></span><br><span class="line"><span class="comment">// 3.发送信号 sendNext:(id)value</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// RACSubject:底层实现和RACSignal不一样。</span></span><br><span class="line"><span class="comment">// 1.调用subscribeNext订阅信号，只是把订阅者保存起来，并且订阅者的nextBlock已经赋值了。</span></span><br><span class="line"><span class="comment">// 2.调用sendNext发送信号，遍历刚刚保存的所有订阅者，一个一个调用订阅者的nextBlock。</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1. 创建信号</span></span><br><span class="line">RACSubject *subject = [RACSubject subject];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2.订阅信号</span></span><br><span class="line">[subject subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">   </span><br><span class="line">    <span class="comment">// block调用时机：当信号发出新值，就会调用</span></span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"收到信号"</span>);</span><br><span class="line">    </span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 3.发送信号</span></span><br><span class="line"><span class="built_in">NSLog</span>(<span class="string">@"发送信号"</span>);</span><br><span class="line">[subject sendNext:<span class="string">@"1"</span>];</span><br></pre></td></tr></table></figure>
 <figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">// RACReplaySubject使用步骤:</span></span><br><span class="line"><span class="comment">// 1.创建信号 [RACSubject subject]，跟RACSiganl不一样，创建信号时没有block。</span></span><br><span class="line"><span class="comment">// 2.可以先订阅信号，也可以先发送信号。</span></span><br><span class="line"><span class="comment">// 2.1 订阅信号 - (RACDisposable *)subscribeNext:(void (^)(id x))nextBlock</span></span><br><span class="line"><span class="comment">// 2.2 发送信号 sendNext:(id)value</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// RACReplaySubject:底层实现和RACSubject不一样。</span></span><br><span class="line"><span class="comment">// 1.调用sendNext发送信号，把值保存起来，然后遍历刚刚保存的所有订阅者，一个一个调用订阅者的nextBlock。</span></span><br><span class="line"><span class="comment">// 2.调用subscribeNext订阅信号，遍历保存的所有值，一个一个调用订阅者的nextBlock</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果想当一个信号被订阅，就重复播放之前所有值，需要先发送信号，在订阅信号。</span></span><br><span class="line"><span class="comment">// 也就是先保存值，在订阅值。</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1.创建信号</span></span><br><span class="line">RACReplaySubject *replaySubject = [RACReplaySubject subject];</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 3.先订阅信号</span></span><br><span class="line">[<span class="meta">replaySubject subscribeNext:^(id x) &#123;</span></span><br><span class="line"><span class="meta">    </span></span><br><span class="line"><span class="meta">    NSLog(@<span class="meta-string">"第一个订阅者接受到的数据%@"</span>, x);</span></span><br><span class="line"><span class="meta">&#125;</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2.发送信号</span></span><br><span class="line">[<span class="meta">replaySubject sendNext:@1</span>];</span><br><span class="line">[<span class="meta">replaySubject sendNext:@2</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 后订阅信号</span></span><br><span class="line">[<span class="meta">replaySubject subscribeNext:^(id x) &#123;</span></span><br><span class="line"><span class="meta">    </span></span><br><span class="line"><span class="meta">    NSLog(@<span class="meta-string">"第二个订阅者接收到的数据%@"</span>,x);</span></span><br><span class="line"><span class="meta">&#125;</span>];</span><br></pre></td></tr></table></figure>
<p><strong>RACSubject</strong>替换代理（与block类似）</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 需求:</span></span><br><span class="line">    <span class="comment">// 1.给当前控制器添加一个按钮，modal到另一个控制器界面</span></span><br><span class="line">    <span class="comment">// 2.另一个控制器view中有个按钮，点击按钮，通知当前控制器</span></span><br><span class="line"></span><br><span class="line">步骤一：在第二个控制器.h，添加一个RACSubject代替代理。</span><br><span class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">TwoViewController</span> : <span class="title">UIViewController</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>, <span class="keyword">strong</span>) RACSubject *delegateSignal;</span><br><span class="line"></span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line">步骤二：监听第二个控制器按钮点击</span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">TwoViewController</span></span></span><br><span class="line">- (<span class="keyword">IBAction</span>)notice:(<span class="keyword">id</span>)sender &#123;</span><br><span class="line">    <span class="comment">// 通知第一个控制器，告诉它，按钮被点了</span></span><br><span class="line"></span><br><span class="line">     <span class="comment">// 通知代理</span></span><br><span class="line">     <span class="comment">// 判断代理信号是否有值</span></span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">self</span>.delegateSignal) &#123;</span><br><span class="line">        <span class="comment">// 有值，才需要通知</span></span><br><span class="line">        [<span class="keyword">self</span>.delegateSignal sendNext:<span class="literal">nil</span>];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">@end</span></span><br><span class="line"></span><br><span class="line">步骤三：在第一个控制器中，监听跳转按钮，给第二个控制器的代理信号赋值，并且监听.</span><br><span class="line"><span class="class"><span class="keyword">@implementation</span> <span class="title">OneViewController</span> </span></span><br><span class="line">- (<span class="keyword">IBAction</span>)btnClick:(<span class="keyword">id</span>)sender &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 创建第二个控制器</span></span><br><span class="line">    TwoViewController *twoVc = [[TwoViewController alloc] init];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 设置代理信号</span></span><br><span class="line">    twoVc.delegateSignal = [RACSubject subject];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 订阅代理信号</span></span><br><span class="line">    [twoVc.delegateSignal subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line"></span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@"点击了通知按钮 %@"</span>, x);</span><br><span class="line">    &#125;];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 跳转到第二个控制器</span></span><br><span class="line">    [<span class="keyword">self</span> presentViewController:twoVc animated:<span class="literal">YES</span> completion:<span class="string">@"hi"</span>];</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">@end</span></span><br></pre></td></tr></table></figure>
<h4 id="RACTuple"><a href="#RACTuple" class="headerlink" title="RACTuple"></a>RACTuple</h4><blockquote>
<p>元组类,类似NSArray,用来包装值.(<code>@[key, value]</code>)</p>
</blockquote>
<h4 id="RACSequence"><a href="#RACSequence" class="headerlink" title="RACSequence"></a>RACSequence</h4><blockquote>
<p>RAC中的集合类，用于代替NSArray,NSDictionary,可以使用它来快速遍历数组和字典。</p>
</blockquote>
<p>使用场景：字典转模型</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1.遍历数组</span></span><br><span class="line"><span class="built_in">NSArray</span> *numbers = @[@<span class="number">1</span>,@<span class="number">2</span>,@<span class="number">3</span>,@<span class="number">4</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 这里其实是三步</span></span><br><span class="line"><span class="comment">// 第一步: 把数组转换成集合RACSequence numbers.rac_sequence</span></span><br><span class="line"><span class="comment">// 第二步: 把集合RACSequence转换RACSignal信号类,numbers.rac_sequence.signal</span></span><br><span class="line"><span class="comment">// 第三步: 订阅信号，激活信号，会自动把集合中的所有值，遍历出来。</span></span><br><span class="line"></span><br><span class="line">[numbers.rac_sequence.signal subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"%@"</span>, x);</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 2.遍历字典,遍历出来的键值对 都会包装成 RACTuple(元组对象) @[key, value]</span></span><br><span class="line"><span class="built_in">NSDictionary</span> *dic = @&#123;<span class="string">@"name"</span>: <span class="string">@"BYqiu"</span>, <span class="string">@"age"</span>: @<span class="number">18</span>&#125;;</span><br><span class="line"></span><br><span class="line">[dic.rac_sequence.signal subscribeNext:^(RACTuple *x) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 解元组包，会把元组的值，按顺序给参数里的变量赋值</span></span><br><span class="line">    <span class="comment">// 写法相当与</span></span><br><span class="line">    <span class="comment">// NSString *key = x[0];</span></span><br><span class="line">    <span class="comment">// NSString *value = x[1];</span></span><br><span class="line">    RACTupleUnpack(<span class="built_in">NSString</span> *key, <span class="built_in">NSString</span> *value) = x;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"key:%@, value:%@"</span>, key, value);</span><br><span class="line">    </span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 3.字典转模型</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">NSString</span> *filePath = [[<span class="built_in">NSBundle</span> mainBundle] pathForResource:<span class="string">@"flags.plist"</span> ofType:<span class="literal">nil</span>];</span><br><span class="line"></span><br><span class="line"><span class="built_in">NSArray</span> *dicArray = [<span class="built_in">NSArray</span> arrayWithContentsOfFile:filePath];</span><br><span class="line"></span><br><span class="line"><span class="built_in">NSMutableArray</span> *items = [<span class="built_in">NSMutableArray</span> array];</span><br><span class="line"></span><br><span class="line"><span class="comment">// OC写法</span></span><br><span class="line"><span class="keyword">for</span> (<span class="built_in">NSDictionary</span> *dic <span class="keyword">in</span> dicArray) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//FlagItem *item = [FlagItem flagWithDict:dict];</span></span><br><span class="line">    <span class="comment">//[items addObject:item];</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// RAC写法</span></span><br><span class="line">[dicArray.rac_sequence.signal subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">    <span class="comment">// 利用RAC遍历， x：字典</span></span><br><span class="line">    </span><br><span class="line">    <span class="comment">//FlagItem *item = [FlagItem flagWithDict:x];</span></span><br><span class="line">    <span class="comment">//[items addObject:item];</span></span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// RAC高级用法（函数式编程）</span></span><br><span class="line"><span class="built_in">NSArray</span> *flags = [[dicArray.rac_sequence map:^<span class="keyword">id</span>(<span class="keyword">id</span> value) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span>  [FlagItem flagWithDict:value];</span><br><span class="line">    </span><br><span class="line">&#125;] array];</span><br></pre></td></tr></table></figure>
<h4 id="RACCommand"><a href="#RACCommand" class="headerlink" title="RACCommand"></a>RACCommand</h4><blockquote>
<p>RAC中用于处理事件的类，可以把事件如何处理,事件中的数据如何传递，包装到这个类中，他可以很方便的监控事件的执行过程。</p>
</blockquote>
<p> 一、RACCommand使用步骤:</p>
<ol>
<li>创建命令 initWithSignalBlock:(RACSignal * (^)(id input))signalBlock</li>
<li>在signalBlock中，创建RACSignal，并且作为signalBlock的返回值</li>
<li><p>执行命令 - (RACSignal *)execute:(id)input</p>
<p>二、RACCommand使用注意:</p>
</li>
<li><p>signalBlock必须要返回一个信号，不能传nil.</p>
</li>
<li>如果不想要传递信号，直接创建空的信号[RACSignal empty];</li>
<li>RACCommand中信号如果数据传递完，必须调用[subscriber sendCompleted]，这时命令才会执行完毕，否则永远处于执行中。</li>
<li><p>RACCommand需要被强引用，否则接收不到RACCommand中的信号，因此RACCommand中的信号是延迟发送的。</p>
<p>三、RACCommand设计思想：</p>
<p>内部signalBlock为什么要返回一个信号，这个信号有什么用。</p>
</li>
<li><p>在RAC开发中，通常会把网络请求封装到RACCommand，直接执行某个RACCommand就能发送请求。</p>
</li>
<li><p>当RACCommand内部请求到数据的时候，需要把请求的数据传递给外界，这时候就需要通过signalBlock返回的信号传递了。</p>
<p>四、如何拿到RACCommand中返回信号发出的数据。</p>
</li>
<li><p>RACCommand有个执行信号源executionSignals，这个是signal of signals(信号的信号),意思是信号发出的数据是信号，不是普通的类型。</p>
</li>
<li><p>订阅executionSignals就能拿到RACCommand中返回的信号，然后订阅signalBlock返回的信号，就能获取发出的值。</p>
<p>五、监听当前命令是否正在执行executing</p>
<p>六、使用场景,监听按钮点击，网络请求</p>
</li>
</ol>
<p>使用:</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1.创建命令</span></span><br><span class="line">    RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(<span class="keyword">id</span> input) &#123;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@"执行命令"</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 返回空信号</span></span><br><span class="line">        <span class="comment">//return [RACSignal empty];</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 2.创建信号 传递数据</span></span><br><span class="line">        <span class="keyword">return</span> [RACSignal createSignal:^RACDisposable *(<span class="keyword">id</span>&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">            </span><br><span class="line">            [subscriber sendNext:<span class="string">@"请求数据"</span>];</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// 注意：数据传递完，最好调用sendCompleted,这时命令才执行完毕</span></span><br><span class="line">            [subscriber sendCompleted];</span><br><span class="line">            </span><br><span class="line">            <span class="keyword">return</span> <span class="literal">nil</span>;</span><br><span class="line">        &#125;];</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 强引用命令，不要被销毁，否则接收不到数据</span></span><br><span class="line">    _command = command;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 3.订阅RACCommand的信号</span></span><br><span class="line">    [command.executionSignals subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">        [x subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">            </span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@"订阅RACCommand的信号: %@"</span>, x);</span><br><span class="line">        &#125;];</span><br><span class="line">    &#125;];</span><br><span class="line"></span><br><span class="line">    <span class="comment">// RAC高级用法</span></span><br><span class="line">    <span class="comment">// switchToLatest:用于signal of signals，获取signal of signals发出的最新信号,也就是可以直接拿到RACCommand中的信号</span></span><br><span class="line">    [command.executionSignals.switchToLatest subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">       </span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@"RAC高级用法: %@"</span>, x);</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 4.监听命令是否执行完毕,默认会来一次，可以直接跳过，skip表示跳过第一次信号。</span></span><br><span class="line">    [[command.executing skip:<span class="number">1</span>] subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">       </span><br><span class="line">        <span class="keyword">if</span> ([x boolValue] == <span class="literal">YES</span>) &#123;</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// 正在执行</span></span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@"正在执行"</span>);</span><br><span class="line">            </span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            </span><br><span class="line">            <span class="comment">// 执行完毕</span></span><br><span class="line">            <span class="built_in">NSLog</span>(<span class="string">@"执行完成"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// 5.执行命名</span></span><br><span class="line">    [<span class="keyword">self</span>.command execute:@<span class="number">1</span>];</span><br></pre></td></tr></table></figure>
<h4 id="RACMulticastConnection"><a href="#RACMulticastConnection" class="headerlink" title="RACMulticastConnection"></a>RACMulticastConnection</h4><blockquote>
<p>用于当一个信号，被多次订阅时，为了保证创建信号时，避免多次调用创建信号中的block，造成副作用，可以使用这个类处理。</p>
</blockquote>
<p>注意：RACMulticastConnection通过RACSignal的-publish或者-muticast:方法创建.</p>
<p>RACMulticastConnection使用步骤:</p>
<ol>
<li>创建信号 + (RACSignal <em>)createSignal:(RACDisposable </em> (^)(id<racsubscriber> subscriber))didSubscribe</racsubscriber></li>
<li>创建连接 RACMulticastConnection *connect = [signal publish];</li>
<li>订阅信号,注意：订阅的不在是之前的信号，而是连接的信号。 [connect.signal subscribeNext:nextBlock]</li>
<li>连接 [connect connect]</li>
</ol>
<p>RACMulticastConnection底层原理:</p>
<ol>
<li>创建connect，connect.sourceSignal -&gt; RACSignal(原始信号)  connect.signal -&gt; RACSubject</li>
<li>订阅connect.signal，会调用RACSubject的subscribeNext，创建订阅者，而且把订阅者保存起来，不会执行block。</li>
<li>[connect connect]内部会订阅RACSignal(原始信号)，并且订阅者是RACSubject<ol>
<li>订阅原始信号，就会调用原始信号中的didSubscribe</li>
<li>didSubscribe，拿到订阅者调用sendNext，其实是调用RACSubject的sendNext</li>
</ol>
</li>
<li>RACSubject的sendNext,会遍历RACSubject所有订阅者发送信号。<ul>
<li>因为刚刚第二步，都是在订阅RACSubject，因此会拿到第二步所有的订阅者，调用他们的nextBlock</li>
</ul>
</li>
</ol>
<p>需求：假设在一个信号中发送请求，每次订阅一次都会发送请求，这样就会导致多次请求。</p>
<p>解决：使用RACMulticastConnection就能解决.</p>
<p>问题：每次订阅一次都会发送请求</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建请求信号</span></span><br><span class="line">RACSignal *signal = [RACSignal createSignal:^RACDisposable *(<span class="keyword">id</span>&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"发送请求"</span>);</span><br><span class="line">    [subscriber sendNext:@<span class="number">1</span>];</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">nil</span>;</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 订阅信号</span></span><br><span class="line">[signal subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"接受数据: %@"</span>, x);</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 再次订阅信号，会再次执行发送请求，也就是每次订阅都会发送一次请求</span></span><br><span class="line">[signal subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"接受数据: %@"</span>, x);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">2016<span class="selector-tag">-12-28</span> 11<span class="selector-pseudo">:37</span><span class="selector-pseudo">:04.397</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[1505:340573]</span> 发送请求</span><br><span class="line">2016<span class="selector-tag">-12-28</span> 11<span class="selector-pseudo">:37</span><span class="selector-pseudo">:04.398</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[1505:340573]</span> 接受数据: 1</span><br><span class="line">2016<span class="selector-tag">-12-28</span> 11<span class="selector-pseudo">:37</span><span class="selector-pseudo">:04.398</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[1505:340573]</span> 发送请求</span><br><span class="line">2016<span class="selector-tag">-12-28</span> 11<span class="selector-pseudo">:37</span><span class="selector-pseudo">:04.398</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[1505:340573]</span> 接受数据: 1</span><br></pre></td></tr></table></figure>
<p>可以发现每次订阅都会重新发送请求.</p>
<p>下面我们使用RACMulticastConnection：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">RACSignal *signal = [RACSignal createSignal:^RACDisposable *(<span class="keyword">id</span>&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"发送请求"</span>);</span><br><span class="line">    [subscriber sendNext:@<span class="number">1</span>];</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> <span class="literal">nil</span>;</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建连接</span></span><br><span class="line">RACMulticastConnection *connect = [signal publish];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 订阅信号</span></span><br><span class="line"><span class="comment">// 注意：订阅信号，也不能激活信号，只是保存订阅者到数组，必须通过连接，当调用连接，就会一次性调用所有订阅者的SendNext</span></span><br><span class="line">[connect.signal subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"订阅者1信号: %@"</span>, x);</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line">[connect.signal subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"订阅者2信号: %@"</span>, x);</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="comment">// 连接、激活信号</span></span><br><span class="line">[connect connect];</span><br></pre></td></tr></table></figure>
<p>输出：</p>
<figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">2016<span class="selector-tag">-12-28</span> 11<span class="selector-pseudo">:37</span><span class="selector-pseudo">:04.399</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[1505:340573]</span> 发送请求</span><br><span class="line">2016<span class="selector-tag">-12-28</span> 11<span class="selector-pseudo">:37</span><span class="selector-pseudo">:04.399</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[1505:340573]</span> 订阅者1信号: 1</span><br><span class="line">2016<span class="selector-tag">-12-28</span> 11<span class="selector-pseudo">:37</span><span class="selector-pseudo">:04.399</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[1505:340573]</span> 订阅者2信号: 1</span><br></pre></td></tr></table></figure>
<h4 id="RACScheduler"><a href="#RACScheduler" class="headerlink" title="RACScheduler"></a>RACScheduler</h4><blockquote>
<p>RAC中的队列，用GCD封装的。</p>
</blockquote>
<h4 id="RACUnit"><a href="#RACUnit" class="headerlink" title="RACUnit"></a>RACUnit</h4><blockquote>
<p>表⽰stream不包含有意义的值,也就是看到这个，可以直接理解为nil.</p>
</blockquote>
<h4 id="RACEven"><a href="#RACEven" class="headerlink" title="RACEven"></a>RACEven</h4><blockquote>
<p>把数据包装成信号事件(signal event)。它主要通过RACSignal的-materialize来使用，然并卵。</p>
</blockquote>
<h1 id="ReactiveCocoa开发中常见用法"><a href="#ReactiveCocoa开发中常见用法" class="headerlink" title="ReactiveCocoa开发中常见用法"></a>ReactiveCocoa开发中常见用法</h1><ol>
<li>替换代理            </li>
<li>替换KVO</li>
<li>监听事件</li>
<li>替换通知</li>
<li>监听文本框文字改变</li>
<li>统一处理多个网络请求</li>
</ol>
<h4 id="替换代理："><a href="#替换代理：" class="headerlink" title="替换代理："></a>替换代理：</h4><p><strong>rac_signalForSelector:</strong></p>
<p><code>rac_signalForSelector:</code> 直接监听 <code>Selector</code> 事件的调用</p>
<p>应用场景：监听 <code>RedViewController</code> 中按钮的点击事件 <code>btnTap:</code></p>
<p>跳转到<code>RedViewController</code>前，先使用<code>rac_signalForSelector</code>订阅rvc中的 <code>btnTap:</code> 点击事件</p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用segue跳转</span></span><br><span class="line">- (<span class="keyword">void</span>)<span class="string">prepareForSegue:</span>(UIStoryboardSegue *)segue <span class="string">sender:</span>(id)sender &#123;</span><br><span class="line">- </span><br><span class="line">    <span class="keyword">if</span> ([segue.identifier <span class="string">isEqualToString:</span>@<span class="string">"goRedVC"</span>]) &#123;</span><br><span class="line">        </span><br><span class="line">        RedViewController *rvc = segue.destinationViewController;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 订阅rvc中的 btnTap: 点击事件</span></span><br><span class="line">        [[rvc <span class="string">rac_signalForSelector:</span><span class="meta">@selector</span>(<span class="string">btnTap:</span>)] <span class="string">subscribeNext:</span>^(id x) &#123;</span><br><span class="line">        </span><br><span class="line">            NSLog(@<span class="string">"RedVC btnTap！"</span>);</span><br><span class="line">        &#125;];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><code>RedViewController.m</code> 中的按钮事件</p>
<figure class="highlight erlang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">- <span class="params">(IBAction)</span>btnTap:<span class="params">(id)</span>sender &#123;</span><br><span class="line">    </span><br><span class="line">    NSLog<span class="params">(@<span class="string">"!"</span>)</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="替换KVO"><a href="#替换KVO" class="headerlink" title="替换KVO"></a>替换KVO</h4><p><strong>rac_valuesForKeyPath:</strong></p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// KVO</span></span><br><span class="line"><span class="comment">// 监听 slider 的 value 变化</span></span><br><span class="line">[[<span class="keyword">self</span>.slider rac_valuesForKeyPath:<span class="string">@"value"</span> observer:<span class="literal">nil</span>] subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"slider value Change：%@"</span>, x);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
<h4 id="替换通知"><a href="#替换通知" class="headerlink" title="替换通知"></a>替换通知</h4><p><strong>rac_addObserverForName</strong></p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 原生的订阅通知</span></span><br><span class="line"><span class="selector-attr">[[NSNotificationCenter defaultCenter]</span> <span class="selector-tag">addObserver</span><span class="selector-pseudo">:self</span></span><br><span class="line">                                         <span class="selector-tag">selector</span>:@<span class="selector-tag">selector</span>(<span class="attribute">userDidChange</span>:)</span><br><span class="line">                                             <span class="selector-tag">name</span><span class="selector-pseudo">:kTTCurrentUserLoggedOffNotification</span></span><br><span class="line">                                           <span class="selector-tag">object</span><span class="selector-pseudo">:nil</span>];</span><br><span class="line">                                           </span><br><span class="line"><span class="comment">// 使用RAC订阅通知 ，takeUntil限定信号的声明周期                                  </span></span><br><span class="line"><span class="selector-attr">[[[[NSNotificationCenter defaultCenter]</span> <span class="selector-tag">rac_addObserverForName</span><span class="selector-pseudo">:UIApplicationDidEnterBackgroundNotification</span> <span class="selector-tag">object</span><span class="selector-pseudo">:nil</span>]</span><br><span class="line">  <span class="selector-tag">takeUntil</span>:<span class="selector-attr">[self rac_willDeallocSignal]</span>]</span><br><span class="line">  <span class="selector-tag">subscribeNext</span>:^(id x) &#123;</span><br><span class="line">     <span class="selector-tag">NSLog</span>(@<span class="string">"Notification received"</span>);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
<h4 id="监听事件"><a href="#监听事件" class="headerlink" title="监听事件"></a>监听事件</h4><p><strong>rac_signalForControlEvents:</strong></p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 监听 btn 的 UIControlEventTouchUpInside 点击事件</span></span><br><span class="line">[[<span class="keyword">self</span>.btn rac_signalForControlEvents:<span class="built_in">UIControlEventTouchUpInside</span>] subscribeNext:^(<span class="keyword">id</span> x) &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@"btnTap"</span>);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>
<h4 id="监听-textField-文字变化"><a href="#监听-textField-文字变化" class="headerlink" title="监听 textField 文字变化"></a>监听 textField 文字变化</h4><p><strong>rac_textSignal</strong></p>
<figure class="highlight hy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[[self.textField rac_textSignal] subscribeNext:^(<span class="name"><span class="builtin-name">id</span></span> x) &#123;</span><br><span class="line">        </span><br><span class="line">	NSLog(@<span class="string">"textField change: %@"</span>, x)<span class="comment">;</span></span><br><span class="line">&#125;]<span class="comment">;</span></span><br></pre></td></tr></table></figure>
<h4 id="统一处理多个网络请求"><a href="#统一处理多个网络请求" class="headerlink" title="统一处理多个网络请求"></a>统一处理多个网络请求</h4><p><strong>rac_liftSelector:</strong></p>
<figure class="highlight groovy"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">- (<span class="keyword">void</span>)viewDidLoad &#123;</span><br><span class="line">    [<span class="keyword">super</span> viewDidLoad];</span><br><span class="line">    </span><br><span class="line">	<span class="comment">// 处理多个请求都返回结果的时候，统一处理</span></span><br><span class="line">    <span class="comment">// 如同时进行多个网络请求，每个请求都正确返回时，再去刷新页面</span></span><br><span class="line">    </span><br><span class="line">    RACSignal *signalOne = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 网络请求1</span></span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 返回成功</span></span><br><span class="line">        [subscriber <span class="string">sendNext:</span>@<span class="string">"网络请求1 data"</span>];</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> nil;</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">    RACSignal *signalTwo = [RACSignal <span class="string">createSignal:</span>^RACDisposable *(id&lt;RACSubscriber&gt; subscriber) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 网络请求2</span></span><br><span class="line">        <span class="comment">// ...</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 返回成功</span></span><br><span class="line">        [subscriber <span class="string">sendNext:</span>@<span class="string">"网络请求2 data"</span>];</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> nil;</span><br><span class="line">    &#125;];</span><br><span class="line">    </span><br><span class="line">    [self <span class="string">rac_liftSelector:</span><span class="meta">@selector</span>(<span class="string">updateWithR1:</span><span class="string">R2:</span>) <span class="string">withSignalsFromArray:</span>@[signalOne, signalTwo]];</span><br><span class="line">    </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 更新界面</span></span><br><span class="line">- (<span class="keyword">void</span>)<span class="string">updateWithR1:</span>(id)r1 <span class="string">R2:</span>(id)r2 &#123;</span><br><span class="line"></span><br><span class="line">    NSLog(@<span class="string">"R1:%@, R2：%@ 完成！"</span>, r1, r2);</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="注意："><a href="#注意：" class="headerlink" title="注意："></a><strong>注意</strong>：</h4><ul>
<li><p><code>替换KVO</code>和 <code>监听文本框文字改变</code> 方法在创建监听方法时就会执行一次。</p>
  <figure class="highlight css"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">2016<span class="selector-tag">-12-28</span> 16<span class="selector-pseudo">:53</span><span class="selector-pseudo">:50.746</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[4956:1246592]</span> <span class="selector-tag">slider</span> <span class="selector-tag">value</span> <span class="selector-tag">Change</span>：0<span class="selector-class">.5</span></span><br><span class="line">2016<span class="selector-tag">-12-28</span> 16<span class="selector-pseudo">:53</span><span class="selector-pseudo">:50.748</span> <span class="selector-tag">ReactiveCacoa</span><span class="selector-attr">[4956:1246592]</span> <span class="selector-tag">textField</span> <span class="selector-tag">change</span>:</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用<code>rac_liftSelector</code>时 <code>@selector(updateWithR1:R2:)</code>中的方 <strong>参数个数</strong> 要与 <strong>signal个数</strong> 相同，否则会被断言Crash！</p>
</li>
</ul>

      
    </div>
    
    
    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      
    </div>

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <!--<a href="/tags/ios/" rel="tag"># ios</a>-->
            <a href="/tags/ios/" rel="tag"><i class="fa fa-tag"></i> ios</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/12/21/2016-12-21-Objective-C-Category/" rel="next" title="Objective-C：Category">
                <i class="fa fa-chevron-left"></i> Objective-C：Category
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/01/06/2016-01-06-ReactiveCocoa-进阶/" rel="prev" title="ReactiveCocoa 进阶">
                ReactiveCocoa 进阶 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/ichgo.jpg"
                alt="廖壬" />
            
              <p class="site-author-name" itemprop="name">廖壬</p>
              <p class="site-description motion-element" itemprop="description">Learn to choose, to forsake, to endure loneliness, to resist temptation.</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">391</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">11</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">56</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/liaoren512" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:liaoren512@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5281757990/profile?rightmod=1&wvr=6&mod=personinfo" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-globe"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com" target="_blank" title="Zhihu">
                      
                        <i class="fa fa-fw fa-globe"></i>Zhihu</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#ReactiveCocoa基础"><span class="nav-number">1.</span> <span class="nav-text">ReactiveCocoa基础</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ReactiveCocoa简介"><span class="nav-number">2.</span> <span class="nav-text">ReactiveCocoa简介</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ReactiveCocoa编程思想"><span class="nav-number">3.</span> <span class="nav-text">ReactiveCocoa编程思想</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#响应式编程思想"><span class="nav-number">3.0.0.1.</span> <span class="nav-text">响应式编程思想</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#链式编程思想"><span class="nav-number">3.0.0.2.</span> <span class="nav-text">链式编程思想</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#函数式编程思想"><span class="nav-number">3.0.0.3.</span> <span class="nav-text">函数式编程思想</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#导入ReactiveCocoa"><span class="nav-number">4.</span> <span class="nav-text">导入ReactiveCocoa</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Objective-C"><span class="nav-number">4.0.0.1.</span> <span class="nav-text">Objective-C</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Swift"><span class="nav-number">4.0.0.2.</span> <span class="nav-text">Swift</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ReactiveCocoa常见类"><span class="nav-number">5.</span> <span class="nav-text">ReactiveCocoa常见类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#RACSiganl-信号类"><span class="nav-number">5.0.0.1.</span> <span class="nav-text">RACSiganl 信号类</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACSubscriber"><span class="nav-number">5.0.0.2.</span> <span class="nav-text">RACSubscriber</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACDisposable"><span class="nav-number">5.0.0.3.</span> <span class="nav-text">RACDisposable</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACSubject"><span class="nav-number">5.0.0.4.</span> <span class="nav-text">RACSubject</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACReplaySubject"><span class="nav-number">5.0.0.5.</span> <span class="nav-text">RACReplaySubject</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACTuple"><span class="nav-number">5.0.0.6.</span> <span class="nav-text">RACTuple</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACSequence"><span class="nav-number">5.0.0.7.</span> <span class="nav-text">RACSequence</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACCommand"><span class="nav-number">5.0.0.8.</span> <span class="nav-text">RACCommand</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACMulticastConnection"><span class="nav-number">5.0.0.9.</span> <span class="nav-text">RACMulticastConnection</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACScheduler"><span class="nav-number">5.0.0.10.</span> <span class="nav-text">RACScheduler</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACUnit"><span class="nav-number">5.0.0.11.</span> <span class="nav-text">RACUnit</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#RACEven"><span class="nav-number">5.0.0.12.</span> <span class="nav-text">RACEven</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ReactiveCocoa开发中常见用法"><span class="nav-number">6.</span> <span class="nav-text">ReactiveCocoa开发中常见用法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#替换代理："><span class="nav-number">6.0.0.1.</span> <span class="nav-text">替换代理：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#替换KVO"><span class="nav-number">6.0.0.2.</span> <span class="nav-text">替换KVO</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#替换通知"><span class="nav-number">6.0.0.3.</span> <span class="nav-text">替换通知</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#监听事件"><span class="nav-number">6.0.0.4.</span> <span class="nav-text">监听事件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#监听-textField-文字变化"><span class="nav-number">6.0.0.5.</span> <span class="nav-text">监听 textField 文字变化</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#统一处理多个网络请求"><span class="nav-number">6.0.0.6.</span> <span class="nav-text">统一处理多个网络请求</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#注意："><span class="nav-number">6.0.0.7.</span> <span class="nav-text">注意：</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        
<!--<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>-->

<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">廖壬</span>

  
</div>

<!-- 在网站底部加上访问量-->
<!--<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_pv"></span>
</span>
</div>-->
<!--pv的方式，单个用户连续点击n篇文章，记录n次访问量-->
<!--

  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>



-->
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共字</span>
</div>
        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  



  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>